package com.ebupt.migu.music.system.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.ebupt.migu.music.common.entity.Page;
import com.ebupt.migu.music.common.entity.ResultObject;
import com.ebupt.migu.music.common.exception.MyException;
import com.ebupt.migu.music.common.exception.StatusEnum;
import com.ebupt.migu.music.common.util.DateUtil;
import com.ebupt.migu.music.system.entity.SysUser;
import com.ebupt.migu.music.system.mapper.UserMapper;

import lombok.extern.slf4j.Slf4j;

@Service
@Transactional(rollbackFor = MyException.class)
@Slf4j
public class UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 手机号校验编译
     */
    // private static final Pattern MOBILE_PATTERN = Pattern.compile("^(13\\d|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18\\d|19[0-35-9])\\d{8}$");
    private static final Pattern MOBILE_PATTERN = Pattern.compile("^1[0-9]{10}$");

    /**
     * 分页查询用户
     *
     * @param paramMap
     * @return
     */
    public Page<SysUser> queryByPage(Map<String, Object> paramMap) {
        try {
            Page<SysUser> page = new Page<>();
            List<SysUser> list = userMapper.queryByPage(paramMap);
            // 手机号、邮箱敏感信息过滤
            if (list.size() > 0) {
                list.forEach(user -> {
                    user.setMobile(phoneMask(user.getMobile()));
                    user.setEmail(emailMask(user.getEmail()));
                });
            }
            Integer total = userMapper.queryCount(paramMap);
            page.setTotal(total);
            page.setData(list);
            return page;
        } catch (Exception e) {
            throw new MyException(StatusEnum.ERROR, e.getMessage());
        }
    }

    /**
     * 邮箱脱敏处理
     *
     * @param email 邮箱
     * @return 脱敏后的邮箱
     */
    public static String emailMask(String email) {
        String res = "";
        if (StringUtils.hasText(email)) {
            int lastIndexOf = email.lastIndexOf("@");
            String emailInfo = email.substring(0, lastIndexOf);
            String endInfo = email.substring(lastIndexOf);
            int length = emailInfo.length();
            StringBuilder sb = new StringBuilder(emailInfo);
            if (length > 3) {
                sb.replace(3, length, "***");
            } else {
                sb.replace(1, length, "**");
            }
            res = sb + endInfo;
        }
        return res;
    }

    /**
     * 手机号脱敏处理
     *
     * @param mobile 手机号
     * @return 脱敏后的手机号
     */
    public static String phoneMask(String mobile) {
        String res = "******";
        if (StringUtils.hasText(mobile)) {
            StringBuilder sb = new StringBuilder(mobile);
            res = sb.replace(2, 8, "******").toString();
        }
        return res;
    }

    /**
     * 查询用户
     *
     * @param loginName
     * @return
     */
    public SysUser getUserByLoginName(String loginName) {
        try {
            Map<String, Object> paramMap = new HashMap<>(3);
            paramMap.put("pageStart", 0);
            paramMap.put("rows", 9999);
            paramMap.put("loginName", loginName);
            List<SysUser> list = userMapper.queryByPage(paramMap);
            if (list.isEmpty()) {
                return null;
            } else {
                return list.get(0);
            }
        } catch (Exception e) {
            throw new MyException(StatusEnum.ERROR, e.getMessage());
        }
    }


    /**
     * 查询用户
     *
     * @param mobile
     * @return
     */
    public SysUser getUserByMobile(String mobile) {
        if (mobile == null || "".equals(mobile)) {
            throw new MyException(StatusEnum.BUSINID, "手机号为空");
        }
        try {
            Map<String, Object> paramMap = new HashMap<>(3);
            paramMap.put("pageStart", 0);
            paramMap.put("rows", 9999);
            paramMap.put("mobile", mobile);

            List<SysUser> list = userMapper.queryByPage(paramMap);
            if (list.size() > 0) {
                return list.get(0);
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();

            throw new MyException(StatusEnum.ERROR, e.getMessage());
        }
    }

    /**
     * 添加用户
     *
     * @param paramMap
     * @return
     */
    public String addUser(Map<String, Object> paramMap) {
        try {
            userMapper.addUser(paramMap);

            String userId = paramMap.get("id").toString();

            if (paramMap.get("roleId") != null) {
                String userRole = "";
                userRole = paramMap.get("roleId").toString();

                String[] roleArr = userRole.split(",");

                for (String roleId : roleArr) {
                    Map<String, Object> userRoleMap = new HashMap<>(2);

                    userRoleMap.put("roleId", roleId);
                    userRoleMap.put("userId", userId);

                    userMapper.addUserRole(userRoleMap);
                }
            }

            return userId;
        } catch (Exception e) {
            e.printStackTrace();

            throw new MyException(StatusEnum.ERROR, e.getMessage());
        }
    }

    /**
     * 添加角色
     *
     * @param paramMap
     * @return
     */
    public String modifyUser(Map<String, Object> paramMap) {
        try {
            String userId = paramMap.get("userId").toString();

            String status = paramMap.get("status") == null ? null : paramMap.get("status").toString();

            // status=3冻结账号，4解锁账号，根据账号有效期设置为1-已激活，2-未激活
            if (status != null && "4".equals(status)) {
                Map<String, Object> map = new HashMap<>();
                map.put("userId", userId);
                map.put("pageStart", 0);
                map.put("rows", 9999);
                List<SysUser> list = userMapper.queryByPage(map);
                SysUser user = list.get(0);

                Date expireT = DateUtil.parseStrToDate(user.getExpireT(), DateUtil.DATE_FORMAT_YYYY_MM_DD);

                if (expireT.compareTo(new Date()) > 0) {
                    paramMap.put("status", "1");
                } else {
                    paramMap.put("status", "2");
                }
            }

            //更新用户信息
            userMapper.modifyUser(paramMap);

            if (paramMap.get("roleId") != null) {
                //更新用户角色
                userMapper.delUserRole(paramMap);

                String userRole = paramMap.get("roleId").toString();

                String[] roleArr = userRole.split(",");

                for (String roleId : roleArr) {
                    Map<String, Object> userRoleMap = new HashMap<>(2);
                    userRoleMap.put("roleId", roleId);
                    userRoleMap.put("userId", userId);
                    userMapper.addUserRole(userRoleMap);
                }
            }
            return userId;
        } catch (Exception e) {
            throw new MyException(StatusEnum.ERROR, e.getMessage());
        }
    }

    /**
     * 删除用户
     *
     * @param paramMap
     * @return
     */
    public Integer delUser(Map<String, Object> paramMap) {
        try {
            userMapper.delUserRole(paramMap);
            return userMapper.delUser(paramMap);
        } catch (Exception e) {
            throw new MyException(StatusEnum.ERROR, e.getMessage());
        }
    }

    /**
     * 用户更新密码
     *
     * @return
     */
    public ResultObject updatePWD(Map<String, Object> param) {
        ResultObject res = new ResultObject();
        String userId = String.valueOf(param.get("userId"));
        String oldPWD = String.valueOf(param.get("oldPWD"));
        String newPWD = String.valueOf(param.get("newPWD"));
        if (0 == userMapper.isUserExist(userId, oldPWD)) {
            res.setCode(StatusEnum.PASSWORD_ERR.getCode());
            res.setMsg(StatusEnum.PASSWORD_ERR.getMsg());
            return res;
        } else {
            userMapper.updatePWD(userId, newPWD);
        }
        res.setCode(StatusEnum.SUCCESS.getCode());
        res.setMsg(StatusEnum.SUCCESS.getMsg());
        return res;
    }

    public ResultObject<String> syncAccount(SysUser sysUser) {
        log.info("当前同步用户信息：{}", sysUser);
        String loginName = sysUser.getLoginName(), mobile = sysUser.getMobile(), creator = sysUser.getCreator(), userName = sysUser.getUserName();
        if (!(StringUtils.hasText(loginName) && StringUtils.hasText(mobile) && StringUtils.hasText(creator) && StringUtils.hasText(userName))) {
            throw new MyException(StatusEnum.BUSINID, "登录账号、姓名、手机号或创建人账号为空");
        }
        // 登录账号重复性验证
        Map<String, Object> login = new HashMap<>(3);
        login.put("pageStart", 0);
        login.put("rows", 9999);
        login.put("loginName", loginName);
        List<SysUser> loginList = userMapper.queryByPage(login);
        if (!loginList.isEmpty()) {
            throw new MyException(StatusEnum.USER_LOGIN_NAME_EXISTS_ERROR, "");
        }

        // 手机号正则校验
        if (!isMobile(mobile)) {
            throw new MyException(StatusEnum.MOBILE_VER_FAIL, "当前手机号不符合校验规则");
        }

        // 手机号重复性验证
        Map<String, Object> phone = new HashMap<>(3);
        phone.put("pageStart", 0);
        phone.put("rows", 9999);
        phone.put("mobile", mobile);

        List<SysUser> phoneList = userMapper.queryByPage(phone);
        if (!phoneList.isEmpty()) {
            throw new MyException(StatusEnum.USER_MOBILE_EXISTS_ERROR, "");
        }

        // 基础数据赋值
        sysUser.setPassword("96e79218965eb72c92a549dd5a330112");
        sysUser.setStatus("1");
        sysUser.setCreateTime(DateUtil.parseDateToStr(new Date(), DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
        sysUser.setDeptId("23");
        sysUser.setDeptName("江苏省短信营销平台");
        sysUser.setEffectTime(DateUtil.parseDateToStr(new Date(), DateUtil.DATE_FORMAT_YYYY_MM_DD));
        sysUser.setExpireT("2029-12-31");

        int id;
        try {
            // 新增用户
            userMapper.syncAccount(sysUser);
            id = sysUser.getId();
            log.info("{}用户的主键为：{}", userName, id);

            // 添加角色权限
            Map<String, Object> userRoleMap = new HashMap<>(2);

            userRoleMap.put("roleId", "7777");
            userRoleMap.put("userId", id);

            userMapper.addUserRole(userRoleMap);
        } catch (Exception e) {
            log.info("用户同步失败：{}", e.getMessage());
            throw new MyException(StatusEnum.ERROR, e.getMessage());
        }

        return new ResultObject<>(StatusEnum.SUCCESS.getCode(), "同步用户成功", Integer.toString(id));
    }

    /**
     * 手机号正则校验
     *
     * @param mobile 手机号
     * @return 校验结果
     */
    public static boolean isMobile(final String mobile) {
        log.info("待校验的手机号：{}", mobile);
        Matcher matcher = MOBILE_PATTERN.matcher(mobile);
        return matcher.matches();
    }

    /**
     * 分页查询用户
     *
     * @return
     */
    public List<HashMap<String, Object>> emails() {
        try {
            return userMapper.queryEmails();
        } catch (Exception e) {
            throw new MyException(StatusEnum.ERROR, e.getMessage());
        }
    }
}
